#include "VListWidgetItemEditDialog.h"
#include "ui_VListWidgetItemEditDialog.h"
#include "VPathEditDialog.h"

#include <QFileDialog>
#include <QMessageBox>

VListWidgetItemEditDialog::VListWidgetItemEditDialog(QWidget *parent, QString source_path, QString text, int type) :
    QDialog(parent),
    ui(new Ui::VListWidgetItemEditDialog)
{
    ui->setupUi(this);
    _type = type;
    if(_type == 0)
    {
        this->setWindowTitle("选择路径");
    }
    else
    {
        this->setWindowTitle("选择文件");
    }
    ui->lineEdit->setText(text);
    _source_path = source_path;

    if(QDir().isRelativePath(text) && text.isEmpty() == false)
    {
        ui->radio_relative->setChecked(true);
    }
    else
    {
        ui->radio_absolute->setChecked(true);
    }
}

VListWidgetItemEditDialog::~VListWidgetItemEditDialog()
{
    delete ui;
}

void VListWidgetItemEditDialog::on_btn_ok_clicked()
{
    if(ui->lineEdit->text().trimmed().isEmpty())
    {
        QMessageBox::warning(this, "警告", "内容为空");
        return;
    }

    _path = ui->lineEdit->text();
    this->accept();
}

void VListWidgetItemEditDialog::on_btn_cancel_clicked()
{
    this->reject();
}

void VListWidgetItemEditDialog::on_btn_select_clicked()
{
    QString path;
    if(_type == VPathEditDialog::TYPE::FILE)
    {
        path = QFileDialog::getOpenFileName(this, "选择文件", ui->lineEdit->text(), _filter);
    }
    else if(_type == VPathEditDialog::TYPE::FOLDER)
    {
        path = QFileDialog::getExistingDirectory(this, "选择路径", ui->lineEdit->text());
    }
    set_path(path);
}

void VListWidgetItemEditDialog::on_radio_absolute_clicked()
{
    set_path(ui->lineEdit->text());
}

void VListWidgetItemEditDialog::on_radio_relative_clicked()
{
    set_path(ui->lineEdit->text());
}

void VListWidgetItemEditDialog::set_path(QString path)
{
    QDir dir;
    dir.setCurrent(QFileInfo(_source_path).path());
    if(path.isEmpty() == false)
    {
        if(ui->radio_absolute->isChecked())
        {
            if(dir.isRelativePath(path))
            {
                dir.cd(path);
                QString absolute = dir.absolutePath();
                ui->lineEdit->setText(absolute);
            }
            else
            {
                ui->lineEdit->setText(path);
            }
        }
        else
        {

            QString relative = dir.relativeFilePath(path);
            if(dir.isRelativePath(relative) == false)
            {
                ui->lineEdit->setText(relative);
            }
            else
            {
                ui->lineEdit->setText("./"+relative);
            }
        }

    }
}
